package com.gxuwz.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo02 {
    public static void main(String[] args) throws Exception {
        //创建fileChannel
        RandomAccessFile aFile = new RandomAccessFile("d:\\home\\01.txt", "rw");
        FileChannel fileChannel = aFile.getChannel();

        //创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(48);

//        position：方法获取 FileChannel 的当前位置
        long position = fileChannel.position();

        System.out.println("position"+position);
        System.out.println(fileChannel.size());

//        截取文件的前 1024 个字节
        fileChannel.truncate(1024);

//        FileChannel.force()方法将通道里尚未写入磁盘的数据强制写到磁盘上

        String newData="hwgqhdqu";

        buffer.clear();

        //向buffer添加数据
        buffer.put(newData.getBytes());
        buffer.flip();

        while (buffer.hasRemaining()){
            //写入数据
            fileChannel.write(buffer);

        }
        fileChannel.close();




    }
}
